// 科技感电机控制器JavaScript代码

// 全局变量
const API_BASE = window.location.origin;
let isConnected = false;
let isMonitoring = false;
let isLogging = false;
let isMotorReady = false; // 电机通信状态
let isUartConnected = false; // UART连接状态
let osType = 'unknown'; // 操作系统类型

// 状态更新间隔
let statusInterval;

// 显示连接状态提示
function showConnectionStatus(type, message) {
    // 创建状态提示元素
    const statusDiv = document.createElement('div');
    statusDiv.className = `connection-status ${type}`;
    statusDiv.innerHTML = `
        <i class="fas ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i>
        <span>${message}</span>
        <button class="close-btn" onclick="this.parentElement.remove()">
            <i class="fas fa-times"></i>
        </button>
    `;
    
    // 添加到连接控制区域
    let targetSection = null;
    
    // 查找包含"连接控制"的section
    const sections = document.querySelectorAll('.section');
    for (let section of sections) {
        const h2 = section.querySelector('h2');
        if (h2 && h2.textContent.includes('连接控制')) {
            targetSection = section;
            break;
        }
    }
    
    if (targetSection) {
        // 移除之前的状态提示
        const existingStatus = targetSection.querySelector('.connection-status');
        if (existingStatus) {
            existingStatus.remove();
        }
        
        // 添加新的状态提示
        const infoBox = targetSection.querySelector('.info-box');
        if (infoBox) {
            targetSection.insertBefore(statusDiv, infoBox);
        } else {
            targetSection.appendChild(statusDiv);
        }
        
        // 5秒后自动隐藏（给用户更多时间阅读）
        setTimeout(() => {
            if (statusDiv.parentElement) {
                statusDiv.style.opacity = '0';
                statusDiv.style.transform = 'translateY(-10px)';
                setTimeout(() => {
                    if (statusDiv.parentElement) {
                        statusDiv.remove();
                    }
                }, 300);
            }
        }, 5000);
    }
}

// 检测操作系统类型
function detectOS() {
    const userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.indexOf('win') !== -1) {
        osType = 'windows';
        addLog('info', '检测到Windows系统');
    } else if (userAgent.indexOf('linux') !== -1) {
        osType = 'linux';
        addLog('info', '检测到Linux系统');
    } else if (userAgent.indexOf('mac') !== -1) {
        osType = 'macos';
        addLog('info', '检测到macOS系统');
    } else {
        osType = 'unknown';
        addLog('warning', '未知操作系统类型');
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    addLog('info', 'Web界面初始化完成');
    detectOS();
    
    // 立即刷新状态，确保页面加载后马上显示实时状态
    refreshStatus().then(() => {
        updateMotorControlButtons(); // 初始化按钮状态
    });
    
    // 每5秒自动刷新状态，后台定期检查
    statusInterval = setInterval(refreshStatus, 5000);
    
    // 添加键盘事件监听
    document.addEventListener('keydown', function(event) {
        // ESC键关闭所有模态框
        if (event.key === 'Escape') {
            closeAllModals();
        }
    });
    
    // 页面可见性变化时立即刷新状态
    document.addEventListener('visibilitychange', function() {
        if (!document.hidden) {
            addLog('info', '页面重新获得焦点，立即刷新状态');
            refreshStatus();
        }
    });
    
    // 窗口获得焦点时立即刷新状态
    window.addEventListener('focus', function() {
        addLog('info', '窗口获得焦点，立即刷新状态');
        refreshStatus();
    });
});

// 刷新状态
async function refreshStatus() {
    try {
        const response = await fetch(`${API_BASE}/api/status`);
        const data = await response.json();
        
        if (data.success) {
            // 更新连接状态
            const wasConnected = isConnected;
            isConnected = data.connected;
            
            // 更新UART连接状态
            const wasUartConnected = isUartConnected;
            isUartConnected = data.uart_connected || false;
            
            // 如果UART连接状态发生变化，记录日志
            if (wasUartConnected !== isUartConnected) {
                if (isUartConnected) {
                    addLog('success', 'UART串口连接状态已更新：已连接');
                } else {
                    addLog('warning', 'UART串口连接状态已更新：未连接');
                }
            }
            
            // 更新电机状态
            const wasMotorReady = isMotorReady;
            if (data.motor_status && data.motor_status.left_motor_state !== 'unknown') {
                isMotorReady = true;
            } else {
                isMotorReady = false;
            }
            
            // 如果连接状态发生变化，记录日志
            if (wasConnected !== isConnected) {
                if (isConnected) {
                    addLog('success', '串口连接状态已建立');
                } else {
                    addLog('warning', '串口连接已断开');
                }
            }
            
            // 如果电机状态发生变化，记录日志
            if (wasMotorReady !== isMotorReady) {
                if (isMotorReady) {
                    addLog('success', '电机设备已检测到');
                } else {
                    addLog('warning', '电机设备未检测到');
                }
            }
            
            updateStatusDisplay(data);
            updateMotorControlButtons();
        } else {
            addLog('error', `状态获取失败: ${data.message || '未知错误'}`);
        }
    } catch (error) {
        addLog('error', `状态刷新失败: ${error.message}`);
    }
}

// 更新状态显示
function updateStatusDisplay(status) {
    // 检查status是否存在
    if (!status) {
        console.error('状态数据为空');
        return;
    }
    
    // 更新连接状态
    const connectionStatus = document.getElementById('connection-status');
    if (connectionStatus) {
        if (status.connected) {
            // 检查是否有电机设备
            if (status.motor_status && status.motor_status.left_motor_state !== 'unknown') {
                connectionStatus.textContent = '电机连接成功';
                connectionStatus.className = 'status-connected';
            } else {
                connectionStatus.textContent = '串口连接成功';
                connectionStatus.className = 'status-warning';
            }
        } else {
            connectionStatus.textContent = '未连接';
            connectionStatus.className = 'status-disconnected';
        }
    }
    
    // 更新监控状态
    const monitoringStatus = document.getElementById('monitoring-status');
    if (monitoringStatus) {
        monitoringStatus.textContent = status.monitoring ? '运行中' : '已停止';
        monitoringStatus.className = status.monitoring ? 'status-running' : 'status-stopped';
    }
    
    // 更新日志状态
    const loggingStatus = document.getElementById('logging-status');
    if (loggingStatus) {
        loggingStatus.textContent = status.logging ? '记录中' : '已停止';
        loggingStatus.className = status.logging ? 'status-running' : 'status-stopped';
    }
    
    // 更新电机状态
    const leftMotorStatus = document.getElementById('left-motor-status');
    const rightMotorStatus = document.getElementById('right-motor-status');
    if (leftMotorStatus) {
        leftMotorStatus.textContent = `${status.left_motor_speed || 0} RPM`;
    }
    if (rightMotorStatus) {
        rightMotorStatus.textContent = `${status.right_motor_speed || 0} RPM`;
    }
    
    // 更新UART状态
    const uartStatus = document.getElementById('uart-status');
    if (uartStatus) {
        if (status.uart_connected) {
            uartStatus.textContent = '已连接';
            uartStatus.className = 'status-connected';
        } else {
            uartStatus.textContent = '未连接';
            uartStatus.className = 'status-disconnected';
        }
    }
    
    // 更新UART监控状态
    const uartMonitorStatus = document.getElementById('uart-monitor-status');
    if (uartMonitorStatus) {
        if (status.uart_monitoring) {
            uartMonitorStatus.textContent = '监控中';
            uartMonitorStatus.className = 'status-running';
        } else {
            uartMonitorStatus.textContent = '停止';
            uartMonitorStatus.className = 'status-stopped';
        }
    }
    
    // 更新运行方向
    const directionStatus = document.getElementById('direction-status');
    if (directionStatus) {
        directionStatus.textContent = status.direction || '停止';
    }
    
    // 更新电机监控信息
    updateMotorMonitoring(status);
}

// 更新电机监控信息
function updateMotorMonitoring(status) {
    // 更新电机配置信息
    updateMotorConfigDisplay(status);
    
    // 更新电机实时信息
    updateMotorRealtimeDisplay(status);
}

// 更新电机配置信息显示
function updateMotorConfigDisplay(status) {
    // 更新左电机最大转速
    const leftMaxSpeed = document.getElementById('left-motor-max-speed');
    if (leftMaxSpeed) {
        const speed = (status.motor_config && status.motor_config.left_motor_max_speed) || 1500;
        leftMaxSpeed.textContent = `${speed} RPM`;
    }
    
    // 更新右电机最大转速
    const rightMaxSpeed = document.getElementById('right-motor-max-speed');
    if (rightMaxSpeed) {
        const speed = (status.motor_config && status.motor_config.right_motor_max_speed) || 1500;
        rightMaxSpeed.textContent = `${speed} RPM`;
    }
    
    // 更新左电机最小转速
    const leftMinSpeed = document.getElementById('left-motor-min-speed');
    if (leftMinSpeed) {
        const speed = (status.motor_config && status.motor_config.left_motor_min_speed) || 0;
        leftMinSpeed.textContent = `${speed} RPM`;
    }
    
    // 更新右电机最小转速
    const rightMinSpeed = document.getElementById('right-motor-min-speed');
    if (rightMinSpeed) {
        const speed = (status.motor_config && status.motor_config.right_motor_min_speed) || 0;
        rightMinSpeed.textContent = `${speed} RPM`;
    }
    
    // 更新默认转速
    const defaultSpeed = document.getElementById('default-speed');
    if (defaultSpeed) {
        const speed = (status.motor_config && status.motor_config.default_speed) || 600;
        defaultSpeed.textContent = `${speed} RPM`;
    }
    
    // 更新加速度
    const acceleration = document.getElementById('acceleration');
    if (acceleration) {
        const acc = (status.motor_config && status.motor_config.acceleration) || 100;
        acceleration.textContent = acc;
    }
    
    // 更新减速度
    const deceleration = document.getElementById('deceleration');
    if (deceleration) {
        const dec = (status.motor_config && status.motor_config.deceleration) || 100;
        deceleration.textContent = dec;
    }
    
    // 更新系统模式
    const systemMode = document.getElementById('system-mode');
    if (systemMode) {
        const mode = (status.motor_config && status.motor_config.system_mode) || 'independent_speed_closed_loop';
        systemMode.textContent = getSystemModeText(mode);
    }
}

// 更新电机实时信息显示
function updateMotorRealtimeDisplay(status) {
    // 更新左电机转速
    const leftSpeed = document.getElementById('left-motor-speed');
    if (leftSpeed) {
        const speed = (status.motor_status && status.motor_status.left_motor_speed) || 0;
        leftSpeed.textContent = `${speed} RPM`;
    }
    
    // 更新右电机转速
    const rightSpeed = document.getElementById('right-motor-speed');
    if (rightSpeed) {
        const speed = (status.motor_status && status.motor_status.right_motor_speed) || 0;
        rightSpeed.textContent = `${speed} RPM`;
    }
    
    // 更新左电机状态
    const leftState = document.getElementById('left-motor-state');
    if (leftState) {
        const state = (status.motor_status && status.motor_status.left_motor_state) || 'unknown';
        leftState.textContent = getMotorStateText(state);
        leftState.className = `motor-realtime-indicator ${state}`;
    }
    
    // 更新右电机状态
    const rightState = document.getElementById('right-motor-state');
    if (rightState) {
        const state = (status.motor_status && status.motor_status.right_motor_state) || 'unknown';
        rightState.textContent = getMotorStateText(state);
        rightState.className = `motor-realtime-indicator ${state}`;
    }
    
    // 更新运行方向
    const direction = document.getElementById('motor-direction');
    if (direction) {
        direction.textContent = status.direction || '停止';
    }
    
    // 更新运行时间
    const runningTime = document.getElementById('running-time');
    if (runningTime) {
        const time = (status.motor_status && status.motor_status.running_time) || 0;
        runningTime.textContent = formatRunningTime(time);
    }
}

// 获取电机状态文本
function getMotorStateText(state) {
    const stateMap = {
        'unknown': '未知',
        'stopped': '停止',
        'running': '运行',
        'fault': '故障'
    };
    return stateMap[state] || '未知';
}

// 获取系统模式文本
function getSystemModeText(mode) {
    const modeMap = {
        // 独立控制模式
        'independent_speed_closed_loop': '独立速度闭环',
        'independent_speed_open_loop': '独立速度开环',
        'independent_position_closed_loop': '独立位置闭环',
        'independent_position_open_loop': '独立位置开环',
        'independent_torque_closed_loop': '独立转矩闭环',
        'independent_torque_open_loop': '独立转矩开环',
        
        // 同步控制模式
        'synchronized_speed_closed_loop': '同步速度闭环',
        'synchronized_speed_open_loop': '同步速度开环',
        'synchronized_position_closed_loop': '同步位置闭环',
        'synchronized_position_open_loop': '同步位置开环',
        'synchronized_torque_closed_loop': '同步转矩闭环',
        'synchronized_torque_open_loop': '同步转矩开环',
        
        // 同源控制模式
        'same_source_speed_closed_loop': '同源速度闭环',
        'same_source_speed_open_loop': '同源速度开环',
        'same_source_position_closed_loop': '同源位置闭环',
        'same_source_position_open_loop': '同源位置开环',
        'same_source_torque_closed_loop': '同源转矩闭环',
        'same_source_torque_open_loop': '同源转矩开环',
        
        // 基本控制模式
        'position_control': '位置控制',
        'speed_control': '速度控制',
        'torque_control': '转矩控制',
        'velocity_control': '速度控制',
        'current_control': '电流控制',
        
        // 特殊模式
        'manual_mode': '手动模式',
        'auto_mode': '自动模式',
        'calibration_mode': '校准模式',
        'test_mode': '测试模式',
        'emergency_stop': '紧急停止',
        'idle_mode': '空闲模式',
        'standby_mode': '待机模式',
        
        // 高级模式
        'trajectory_control': '轨迹控制',
        'force_control': '力控制',
        'impedance_control': '阻抗控制',
        'admittance_control': '导纳控制',
        'hybrid_control': '混合控制',
        'adaptive_control': '自适应控制',
        'fuzzy_control': '模糊控制',
        'neural_control': '神经网络控制',
        
        // 默认值
        'default': '默认模式',
        'unknown': '未知模式'
    };
    return modeMap[mode] || mode;
}

// 格式化运行时间
function formatRunningTime(seconds) {
    if (!seconds || seconds < 0) return '00:00:00';
    
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);
    
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// 立即更新UI状态（不等待API调用）
function updateUIStatusImmediately(configType, configData) {
    if (configType === 'motor') {
        // 立即更新电机配置显示
        if (configData.left_motor_max_speed !== undefined) {
            const element = document.getElementById('left-motor-max-speed');
            if (element) element.textContent = `${configData.left_motor_max_speed} RPM`;
        }
        if (configData.right_motor_max_speed !== undefined) {
            const element = document.getElementById('right-motor-max-speed');
            if (element) element.textContent = `${configData.right_motor_max_speed} RPM`;
        }
        if (configData.left_motor_min_speed !== undefined) {
            const element = document.getElementById('left-motor-min-speed');
            if (element) element.textContent = `${configData.left_motor_min_speed} RPM`;
        }
        if (configData.right_motor_min_speed !== undefined) {
            const element = document.getElementById('right-motor-min-speed');
            if (element) element.textContent = `${configData.right_motor_min_speed} RPM`;
        }
        if (configData.default_speed !== undefined) {
            const element = document.getElementById('default-speed');
            if (element) element.textContent = `${configData.default_speed} RPM`;
        }
        if (configData.acceleration !== undefined) {
            const element = document.getElementById('acceleration');
            if (element) element.textContent = configData.acceleration;
        }
        if (configData.deceleration !== undefined) {
            const element = document.getElementById('deceleration');
            if (element) element.textContent = configData.deceleration;
        }
        if (configData.system_mode !== undefined) {
            const element = document.getElementById('system-mode');
            if (element) element.textContent = getSystemModeText(configData.system_mode);
        }
    }
}

// 串口监控功能
let monitorActive = false;
let monitorInterval = null;

// 启动串口监控
async function startSerialMonitor() {
    if (monitorActive) {
        addLog('warning', '串口监控已在运行中');
        return;
    }
    
    if (!isUartConnected) {
        addLog('error', '请先连接UART串口设备');
        return;
    }
    
    try {
        addLog('info', '正在启动串口监控...');
        
        // 调用后端API启动UART串口监控
        const response = await fetch(`${API_BASE}/api/uart/start-monitor`, {
            method: 'POST'
        });
        const data = await response.json();
        
        if (data.success) {
            monitorActive = true;
            updateMonitorStatus('monitoring');
            addSerialLine('串口监控已启动', 'success');
            addSerialLine('开始实时监控串口数据...', 'info');
            addSerialLine('等待串口设备发送数据...', 'warning');
            
            // 开始定期获取串口数据
            startSerialDataPolling();
            
            addLog('success', '串口监控启动成功');
        } else {
            addLog('error', `串口监控启动失败: ${data.message}`);
        }
    } catch (error) {
        addLog('error', `串口监控启动异常: ${error.message}`);
    }
}

// 停止串口监控
async function stopSerialMonitor() {
    if (!monitorActive) {
        addLog('warning', '串口监控未运行');
        return;
    }
    
    try {
        addLog('info', '正在停止串口监控...');
        
        // 停止数据轮询
        stopSerialDataPolling();
        
        // 调用后端API停止串口监控
        const response = await fetch(`${API_BASE}/api/serial/stop-terminal`, {
            method: 'POST'
        });
        const data = await response.json();
        
        if (data.success) {
            monitorActive = false;
            updateMonitorStatus('connected');
            addSerialLine('串口监控已停止', 'warning');
            
            addLog('success', '串口监控停止成功');
        } else {
            addLog('error', `串口监控停止失败: ${data.message}`);
        }
    } catch (error) {
        addLog('error', `串口监控停止异常: ${error.message}`);
    }
}

// 清空串口监控
function clearSerialMonitor() {
    const monitor = document.getElementById('serial-monitor');
    if (monitor) {
        monitor.innerHTML = '<div class="serial-line"><span class="serial-time">[清空]</span><span class="serial-text">监控显示已清空</span></div>';
    }
    addLog('info', '串口监控显示已清空');
}

// 添加终端行
function addSerialLine(text, type = 'normal') {
    const monitor = document.getElementById('serial-monitor');
    if (!monitor) return;
    
    const line = document.createElement('div');
    line.className = 'serial-line';
    
    const timeSpan = document.createElement('span');
    timeSpan.className = 'serial-time';
    const now = new Date();
    timeSpan.textContent = `[${now.toLocaleTimeString()}]`;
    
    const textSpan = document.createElement('span');
    textSpan.className = 'serial-text';
    textSpan.textContent = text;
    
    if (type === 'error') {
        textSpan.className += ' error';
    } else if (type === 'success') {
        textSpan.className += ' success';
    } else if (type === 'warning') {
        textSpan.className += ' warning';
    } else if (type === 'info') {
        textSpan.className += ' info';
    }
    
    line.appendChild(timeSpan);
    line.appendChild(textSpan);
    monitor.appendChild(line);
    
    // 自动滚动到底部
    monitor.scrollTop = monitor.scrollHeight;
}

// 更新监控状态显示
function updateMonitorStatus(status) {
    const statusElement = document.getElementById('monitor-status');
    if (!statusElement) return;
    
    statusElement.className = 'monitor-status';
    if (status === 'connected') {
        statusElement.textContent = '已连接';
        statusElement.className += ' connected';
    } else if (status === 'monitoring') {
        statusElement.textContent = '监控中';
        statusElement.className += ' monitoring';
    } else {
        statusElement.textContent = '未连接';
    }
}

// 开始串口数据轮询
function startSerialDataPolling() {
    if (monitorInterval) {
        clearInterval(monitorInterval);
    }
    
    // 每2秒获取一次UART串口数据
    monitorInterval = setInterval(async () => {
        try {
            const response = await fetch(`${API_BASE}/api/uart/receive`);
            const data = await response.json();
            
            if (data.success && data.data && data.data.trim()) {
                // 过滤掉错误信息，只显示真正的串口数据
                const serialData = data.data.trim();
                if (!serialData.startsWith('错误:') && 
                    !serialData.startsWith('无数据') && 
                    serialData !== '') {
                    addSerialLine(serialData, 'info');
                } else if (serialData.startsWith('错误:')) {
                    // 显示错误信息，但用不同的颜色
                    addSerialLine(serialData, 'error');
                }
            }
        } catch (error) {
            // 静默处理轮询错误，避免过多日志
        }
    }, 2000);
}

// 停止串口数据轮询
function stopSerialDataPolling() {
    if (monitorInterval) {
        clearInterval(monitorInterval);
        monitorInterval = null;
    }
}

// 发送串口指令
async function sendSerialCommand() {
    const commandInput = document.getElementById('serial-command');
    const command = commandInput.value.trim();
    
    if (!command) {
        addLog('warning', '请输入要发送的指令');
        return;
    }
    
    if (!isUartConnected) {
        addLog('error', 'UART串口未连接，无法发送指令');
        return;
    }
    
    try {
        addLog('info', `发送指令: ${command}`);
        
        const response = await fetch(`${API_BASE}/api/uart/send`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ command: command })
        });
        
        const data = await response.json();
        
        if (data.success) {
            addLog('success', `指令发送成功: ${command}`);
            if (data.result && data.result !== '无响应') {
                addLog('info', `响应: ${data.result}`);
            }
        } else {
            addLog('error', `指令发送失败: ${data.message || '未知错误'}`);
        }
        
        // 清空输入框
        commandInput.value = '';
        
    } catch (error) {
        addLog('error', `发送指令异常: ${error.message}`);
    }
}

// 处理串口指令输入框的按键事件
function handleSerialKeyPress(event) {
    if (event.key === 'Enter') {
        sendSerialCommand();
    }
}

// 连接电机
async function connectMotor() {
    showLoading('connect-text', 'connect-loading');
    addLog('info', '正在连接电机...');
    
    try {
        addLog('info', '步骤1: 建立串口连接...');
        const response = await fetch(`${API_BASE}/api/connect`, {
            method: 'POST'
        });
        const data = await response.json();
        
        if (data.success) {
            isConnected = true;
            updateMonitorStatus('connected');
            addLog('success', '步骤1完成: 串口连接成功');
            
            // 立即更新状态显示
            await refreshStatus();
            
            // 测试电机通信
            addLog('info', '步骤2: 检测电机设备...');
            await testMotorCommunication();
            
            // 再次更新状态显示，显示最终的连接结果
            await refreshStatus();
        } else {
            isConnected = false;
            addLog('error', `步骤1失败: 串口连接失败 - ${data.message}`);
            addLog('info', '提示：请检查串口配置和设备连接');
        }
    } catch (error) {
        isConnected = false;
        addLog('error', `连接异常: ${error.message}`);
        addLog('info', '提示：请检查网络连接和服务器状态');
    } finally {
        hideLoading('connect-text', 'connect-loading');
        refreshStatus();
        updateMotorControlButtons();
    }
}

// 测试串口连接
async function testSerialConnection() {
    try {
        const response = await fetch(`${API_BASE}/api/status`);
        const data = await response.json();
        
        if (data.success) {
            if (data.connected) {
                addLog('success', '串口连接成功');
                // 检查电机状态
                if (data.motor_status && data.motor_status.left_motor_state !== 'unknown') {
                    addLog('success', '电机设备已检测到');
                } else {
                    addLog('warning', '串口已连接，但未检测到电机设备');
                }
                // 立即刷新状态显示
                updateStatusDisplay(data);
                updateMotorControlButtons();
            } else {
                addLog('warning', '串口连接失败，请检查串口配置');
                updateStatusDisplay(data);
            }
        } else {
            addLog('error', '串口连接测试失败');
        }
    } catch (error) {
        addLog('error', `串口连接测试异常: ${error.message}`);
    }
}

// 测试电机通信
async function testMotorCommunication() {
    try {
        const response = await fetch(`${API_BASE}/api/status`);
        const data = await response.json();
        
        if (data.success && data.connected) {
            // 检查是否有电机状态信息
            if (data.motor_status && data.motor_status.left_motor_state !== 'unknown') {
                isMotorReady = true;
                addLog('success', '步骤2完成: 电机设备检测成功');
                addLog('success', '连接完成: 电机连接成功，可以开始控制');
            } else {
                isMotorReady = false;
                addLog('warning', '步骤2完成: 串口连接成功，但未检测到电机设备');
                addLog('info', '提示：请检查电机控制器是否已连接并上电');
            }
        } else {
            isMotorReady = false;
            addLog('error', `步骤2失败: 电机通信测试失败 - ${data.message || '连接失败'}`);
        }
    } catch (error) {
        isMotorReady = false;
        addLog('error', `步骤2异常: 电机通信测试异常 - ${error.message}`);
    }
}

// 更新电机控制按钮状态
function updateMotorControlButtons() {
    const speedButton = document.querySelector('button[onclick="setSpeed()"]');
    const directionButtons = document.querySelectorAll('button[onclick*="MotorDirection"]');
    const stopButton = document.querySelector('button[onclick="stopMotor()"]');
    
    const isEnabled = isConnected && isMotorReady;
    
    if (speedButton) {
        speedButton.disabled = !isEnabled;
        speedButton.style.opacity = isEnabled ? '1' : '0.5';
    }
    
    directionButtons.forEach(button => {
        button.disabled = !isEnabled;
        button.style.opacity = isEnabled ? '1' : '0.5';
    });
    
    if (stopButton) {
        stopButton.disabled = !isEnabled;
        stopButton.style.opacity = isEnabled ? '1' : '0.5';
    }
    
    // 更新状态显示
    const motorStatus = document.getElementById('motor-status');
    if (motorStatus) {
        if (isEnabled) {
            motorStatus.textContent = '电机就绪';
            motorStatus.style.color = '#4ecdc4';
        } else if (isConnected) {
            motorStatus.textContent = '通信异常';
            motorStatus.style.color = '#ffd93d';
        } else {
            motorStatus.textContent = '未连接';
            motorStatus.style.color = '#ff6b6b';
        }
    }
}

// 断开连接
async function disconnectMotor() {
    addLog('info', '正在断开连接...');
    
    try {
        const response = await fetch(`${API_BASE}/api/disconnect`, {
            method: 'POST'
        });
        const data = await response.json();
        
        if (data.success) {
            isConnected = false;
            isMotorReady = false;
            updateMonitorStatus('disconnected');
            stopSerialDataPolling();
            addLog('success', '连接已断开');
        } else {
            addLog('error', `断开失败: ${data.message}`);
        }
    } catch (error) {
        addLog('error', `断开异常: ${error.message}`);
    } finally {
        refreshStatus();
        updateMotorControlButtons();
    }
}

// 设置转速
async function setSpeed() {
    if (!isConnected || !isMotorReady) {
        addLog('warning', '请先连接电机并确保通信正常');
        return;
    }
    
    const leftSpeed = document.getElementById('left-speed-input').value;
    const rightSpeed = document.getElementById('right-speed-input').value;
    
    if (!leftSpeed || !rightSpeed) {
        addLog('warning', '请输入左右电机转速');
        return;
    }
    
    addLog('info', `设置转速: 左=${leftSpeed} RPM, 右=${rightSpeed} RPM`);
    
    try {
        const response = await fetch(`${API_BASE}/api/motor/speed`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                left_speed: parseInt(leftSpeed),
                right_speed: parseInt(rightSpeed)
            })
        });
        const data = await response.json();
        
        if (data.success) {
            addLog('success', '转速设置成功');
        } else {
            addLog('error', `设置失败: ${data.message}`);
        }
    } catch (error) {
        addLog('error', `设置异常: ${error.message}`);
    } finally {
        refreshStatus();
    }
}

// 重置转速
function resetSpeed() {
    document.getElementById('left-speed-input').value = 500;
    document.getElementById('right-speed-input').value = 500;
    addLog('info', '转速已重置为默认值');
}

// 方向控制函数
async function forwardMotor() {
    addLog('info', '执行前进命令');
    await executeMotorCommand('forward');
}

async function backwardMotor() {
    addLog('info', '执行后退命令');
    await executeMotorCommand('backward');
}

async function leftMotor() {
    addLog('info', '执行左转命令');
    await executeMotorCommand('left');
}

async function rightMotor() {
    addLog('info', '执行右转命令');
    await executeMotorCommand('right');
}

async function stopMotor() {
    addLog('info', '执行停止命令');
    await executeMotorCommand('stop');
}

// 执行电机命令
async function executeMotorCommand(command) {
    if (!isConnected || !isMotorReady) {
        addLog('warning', '请先连接电机并确保通信正常');
        return;
    }
    
    try {
        const response = await fetch(`${API_BASE}/api/motor/${command}`, {
            method: 'POST'
        });
        const data = await response.json();
        
        if (data.success) {
            addLog('success', `${command}命令执行成功`);
        } else {
            addLog('error', `${command}命令执行失败: ${data.message}`);
        }
    } catch (error) {
        addLog('error', `${command}命令异常: ${error.message}`);
    } finally {
        refreshStatus();
    }
}

// 启动监控
async function startMonitoring() {
    addLog('info', '启动监控...');
    await executeMonitorCommand('start');
}

// 停止监控
async function stopMonitoring() {
    addLog('info', '停止监控...');
    await executeMonitorCommand('stop');
}

// 执行监控命令
async function executeMonitorCommand(command) {
    try {
        const response = await fetch(`${API_BASE}/api/monitor/${command}`, {
            method: 'POST'
        });
        const data = await response.json();
        
        if (data.success) {
            addLog('success', `监控${command === 'start' ? '启动' : '停止'}成功`);
        } else {
            addLog('error', `监控${command === 'start' ? '启动' : '停止'}失败: ${data.message}`);
        }
    } catch (error) {
        addLog('error', `监控命令异常: ${error.message}`);
    } finally {
        refreshStatus();
    }
}

// 启动日志记录
async function startLogging() {
    addLog('info', '启动日志记录...');
    await executeLogCommand('start');
}

// 停止日志记录
async function stopLogging() {
    addLog('info', '停止日志记录...');
    await executeLogCommand('stop');
}

// 执行日志命令
async function executeLogCommand(command) {
    try {
        const response = await fetch(`${API_BASE}/api/log/${command}`, {
            method: 'POST'
        });
        const data = await response.json();
        
        if (data.success) {
            addLog('success', `日志记录${command === 'start' ? '启动' : '停止'}成功`);
        } else {
            addLog('error', `日志记录${command === 'start' ? '启动' : '停止'}失败: ${data.message}`);
        }
    } catch (error) {
        addLog('error', `日志命令异常: ${error.message}`);
    } finally {
        refreshStatus();
    }
}

// 清空日志
function clearLogs() {
    const logContent = document.getElementById('log-content');
    if (logContent) {
        logContent.innerHTML = '';
        addLog('info', '日志已清空');
    }
}

// 添加日志
function addLog(type, message) {
    const logContent = document.getElementById('log-content');
    if (!logContent) return;
    
    const timestamp = new Date().toLocaleTimeString();
    const logEntry = document.createElement('div');
    logEntry.className = `log-entry log-${type}`;
    
    logEntry.innerHTML = `
        <span class="log-timestamp">[${timestamp}]</span>
        <span class="log-message">${message}</span>
    `;
    
    logContent.appendChild(logEntry);
    logContent.scrollTop = logContent.scrollHeight;
}

// 显示加载状态
function showLoading(textId, loadingId) {
    const textElement = document.getElementById(textId);
    const loadingElement = document.getElementById(loadingId);
    
    if (textElement) textElement.style.display = 'none';
    if (loadingElement) loadingElement.style.display = 'inline-block';
}

// 隐藏加载状态
function hideLoading(textId, loadingId) {
    const textElement = document.getElementById(textId);
    const loadingElement = document.getElementById(loadingId);
    
    if (textElement) textElement.style.display = 'inline';
    if (loadingElement) loadingElement.style.display = 'none';
}

// 串口配置对话框
function showSerialConfigDialog() {
    const modal = document.getElementById('serial-config-modal');
    if (modal) {
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
        loadSerialConfig();
    }
}

function closeSerialConfigDialog() {
    const modal = document.getElementById('serial-config-modal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
}

// 加载串口配置
async function loadSerialConfig() {
    try {
        const response = await fetch(`${API_BASE}/api/config/serial`);
        const data = await response.json();
        
        if (data.success) {
            const config = data.config;
            document.getElementById('serial-port').value = config.port || '';
            document.getElementById('serial-baudrate').value = config.baudrate || 9600;
            document.getElementById('serial-device-id').value = config.device_id || 1;
            document.getElementById('serial-timeout').value = config.timeout || 1.0;
            document.getElementById('serial-bytesize').value = config.bytesize || 8;
            document.getElementById('serial-parity').value = config.parity || 'N';
            document.getElementById('serial-stopbits').value = config.stopbits || 1;
            document.getElementById('serial-xonxoff').value = config.xonxoff || false;
        }
    } catch (error) {
        addLog('error', `加载串口配置失败: ${error.message}`);
    }
}

// 应用串口配置
async function applySerialConfig() {
    const config = {
        port: document.getElementById('serial-port').value,
        baudrate: parseInt(document.getElementById('serial-baudrate').value),
        device_id: parseInt(document.getElementById('serial-device-id').value),
        timeout: parseFloat(document.getElementById('serial-timeout').value),
        bytesize: parseInt(document.getElementById('serial-bytesize').value),
        parity: document.getElementById('serial-parity').value,
        stopbits: parseInt(document.getElementById('serial-stopbits').value),
        xonxoff: document.getElementById('serial-xonxoff').value === 'true'
    };
    
    try {
        addLog('info', '正在设置串口配置...');
        const response = await fetch(`${API_BASE}/api/config/serial`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(config)
        });
        const data = await response.json();
        
        if (data.success) {
            addLog('success', '串口配置设置成功');
            
            // 保存配置
            addLog('info', '正在保存配置...');
            const saveResponse = await fetch(`${API_BASE}/api/config/save`, {
                method: 'POST'
            });
            if (saveResponse.ok) {
                addLog('success', '配置保存成功');
                addLog('info', '提示：请先点击"测试连接"按钮测试串口连接，然后点击"连接电机"按钮检测电机设备');
                
                // 立即刷新状态，提供即时反馈
                await refreshStatus();
            } else {
                addLog('error', '配置保存失败');
            }
            
            closeSerialConfigDialog();
        } else {
            addLog('error', `串口配置设置失败: ${data.message}`);
        }
    } catch (error) {
        addLog('error', `串口配置设置异常: ${error.message}`);
    }
}

// 测试串口连接
async function testSerialConnection() {
    try {
        addLog('info', '正在测试串口配置...');
        
        // 使用新的测试串口配置API
        const testResponse = await fetch(`${API_BASE}/api/test-serial`, {
            method: 'POST'
        });
        const testData = await testResponse.json();
        
        if (testData.success && testData.can_connect) {
            addLog('success', '串口配置测试成功');
            showConnectionStatus('success', '当前串口可正常连接');
            addLog('info', '提示：请先点击"保存配置"按钮保存配置，然后点击"连接电机"按钮建立连接');
        } else {
            addLog('error', `串口配置测试失败: ${testData.message}`);
            showConnectionStatus('error', '当前串口不能正常连接');
            addLog('info', '提示：请检查串口配置和设备连接');
        }
    } catch (error) {
        addLog('error', `串口配置测试异常: ${error.message}`);
        showConnectionStatus('error', '串口配置测试异常');
    }
}

// 电机配置对话框
function showMotorConfigDialog() {
    const modal = document.getElementById('motor-config-modal');
    if (modal) {
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
        loadMotorConfig();
    }
}

function closeMotorConfigDialog() {
    const modal = document.getElementById('motor-config-modal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
}

// 加载电机配置
async function loadMotorConfig() {
    try {
        const response = await fetch(`${API_BASE}/api/config/motor`);
        const data = await response.json();
        
        if (data.success) {
            const config = data.config;
            document.getElementById('motor-system-mode').value = config.system_mode || 'independent_speed_closed_loop';
            document.getElementById('motor-left-max-speed').value = config.left_motor_max_speed || 1000;
            document.getElementById('motor-right-max-speed').value = config.right_motor_max_speed || 1000;
            document.getElementById('motor-left-min-speed').value = config.left_motor_min_speed || 0;
            document.getElementById('motor-right-min-speed').value = config.right_motor_min_speed || 0;
            document.getElementById('motor-default-speed').value = config.default_speed || 500;
            document.getElementById('motor-acceleration').value = config.acceleration || 100;
            document.getElementById('motor-deceleration').value = config.deceleration || 100;
        }
    } catch (error) {
        addLog('error', `加载电机配置失败: ${error.message}`);
    }
}

// 应用电机配置
async function applyMotorConfig() {
    const config = {
        system_mode: document.getElementById('motor-system-mode').value,
        left_motor_max_speed: parseInt(document.getElementById('motor-left-max-speed').value),
        right_motor_max_speed: parseInt(document.getElementById('motor-right-max-speed').value),
        left_motor_min_speed: parseInt(document.getElementById('motor-left-min-speed').value),
        right_motor_min_speed: parseInt(document.getElementById('motor-right-min-speed').value),
        default_speed: parseInt(document.getElementById('motor-default-speed').value),
        acceleration: parseInt(document.getElementById('motor-acceleration').value),
        deceleration: parseInt(document.getElementById('motor-deceleration').value)
    };
    
    try {
        addLog('info', '正在应用电机配置...');
        const response = await fetch(`${API_BASE}/api/config/motor`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(config)
        });
        const data = await response.json();
        
        if (data.success) {
            addLog('success', '电机配置应用成功');
            
            // 立即更新UI显示，提供即时反馈
            updateUIStatusImmediately('motor', config);
            
            // 自动保存配置
            const saveResponse = await fetch(`${API_BASE}/api/config/save`, {
                method: 'POST'
            });
            if (saveResponse.ok) {
                addLog('info', '配置已自动保存');
                
                // 再次刷新状态，确保数据同步
                await refreshStatus();
            }
            closeMotorConfigDialog();
        } else {
            addLog('error', `电机配置应用失败: ${data.message}`);
        }
    } catch (error) {
        addLog('error', `电机配置应用异常: ${error.message}`);
    }
}

// 配置文件管理对话框
function loadConfig() {
    const modal = document.getElementById('config-load-modal');
    if (modal) {
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
    }
}

function closeConfigLoadDialog() {
    const modal = document.getElementById('config-load-modal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
}

// 加载默认配置
async function loadDefaultConfig() {
    const defaultConfig = {
        "serial": {
            "port": "COM1",
            "baudrate": 9600,
            "device_id": 1,
            "timeout": 1.0,
            "bytesize": 8,
            "parity": "N",
            "stopbits": 1
        }
    };
    
    document.getElementById('config-content').value = JSON.stringify(defaultConfig, null, 2);
    addLog('info', '已加载默认配置模板');
}

// 从文本加载配置
async function loadConfigFromText() {
    const configText = document.getElementById('config-content').value;
    
    if (!configText.trim()) {
        addLog('warning', '请输入配置内容');
        return;
    }
    
    try {
        const config = JSON.parse(configText);
        
        // 应用串口配置
        if (config.serial) {
            const serialResponse = await fetch(`${API_BASE}/api/config/serial`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(config.serial)
            });
            const serialData = await serialResponse.json();
            
            if (serialData.success) {
                addLog('success', '串口配置应用成功');
            } else {
                addLog('error', `串口配置应用失败: ${serialData.message}`);
            }
        }
        
        // 应用电机配置
        if (config.motor) {
            const motorResponse = await fetch(`${API_BASE}/api/config/motor`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(config.motor)
            });
            const motorData = await motorResponse.json();
            
            if (motorData.success) {
                addLog('success', '电机配置应用成功');
            } else {
                addLog('error', `电机配置应用失败: ${motorData.message}`);
            }
        }
        
        // 保存配置
        const saveResponse = await fetch(`${API_BASE}/api/config/save`, {
            method: 'POST'
        });
        
        if (saveResponse.ok) {
            addLog('success', '配置已保存');
        }
        
        closeConfigLoadDialog();
        
    } catch (error) {
        addLog('error', `配置解析失败: ${error.message}`);
    }
}

// 保存配置到文本
async function saveConfigToText() {
    try {
        // 获取当前串口配置
        const serialResponse = await fetch(`${API_BASE}/api/config/serial`);
        const serialData = await serialResponse.json();
        
        // 获取当前电机配置
        const motorResponse = await fetch(`${API_BASE}/api/config/motor`);
        const motorData = await motorResponse.json();
        
        // 构建完整配置
        const fullConfig = {
            serial: serialData.success ? serialData.config : {},
            motor: motorData.success ? motorData.config : {},
            timestamp: new Date().toISOString(),
            version: "1.0.0"
        };
        
        // 显示在文本框中
        document.getElementById('config-content').value = JSON.stringify(fullConfig, null, 2);
        addLog('success', '当前配置已加载到文本框');
        
    } catch (error) {
        addLog('error', `保存配置失败: ${error.message}`);
    }
}

// 扫描串口
async function scanSerialPorts() {
    addLog('info', '正在扫描可用串口...');
    
    try {
        const response = await fetch(`${API_BASE}/api/scan-ports`);
        const data = await response.json();
        
        if (data.success && data.ports && data.ports.length > 0) {
            const portSelect = document.getElementById('serial-port');
            const detectedDiv = document.getElementById('detected-ports');
            
            // 清空现有选项
            portSelect.innerHTML = '';
            
            // 根据操作系统类型设置默认端口
            let defaultPort = '';
            if (osType === 'windows') {
                defaultPort = 'COM1';
            } else if (osType === 'linux') {
                defaultPort = '/dev/ttyUSB0';
            } else if (osType === 'macos') {
                defaultPort = '/dev/tty.usbserial';
            }
            
            // 添加检测到的端口
            data.ports.forEach(port => {
                const option = document.createElement('option');
                option.value = port;
                option.textContent = port;
                if (port === defaultPort) {
                    option.selected = true;
                    option.textContent += ' (推荐)';
                }
                portSelect.appendChild(option);
            });
            
            // 如果没有检测到推荐端口，选择第一个
            if (!defaultPort || !data.ports.includes(defaultPort)) {
                portSelect.selectedIndex = 0;
            }
            
            // 显示检测结果
            detectedDiv.innerHTML = `检测到 ${data.ports.length} 个串口: ${data.ports.join(', ')}`;
            detectedDiv.style.color = '#4ecdc4';
            
            addLog('success', `检测到 ${data.ports.length} 个串口: ${data.ports.join(', ')}`);
        } else {
            const detectedDiv = document.getElementById('detected-ports');
            detectedDiv.innerHTML = '未检测到可用串口';
            detectedDiv.style.color = '#ff6b6b';
            addLog('warning', '未检测到可用串口');
        }
    } catch (error) {
        const detectedDiv = document.getElementById('detected-ports');
        detectedDiv.innerHTML = '扫描失败: ' + error.message;
        detectedDiv.style.color = '#ff6b6b';
        addLog('error', `串口扫描失败: ${error.message}`);
    }
}

// 关闭所有模态框
function closeAllModals() {
    const modals = ['serial-config-modal', 'motor-config-modal', 'config-load-modal', 'logging-config-modal'];
    modals.forEach(modalId => {
        const modal = document.getElementById(modalId);
        if (modal) {
            modal.classList.add('hidden');
            modal.style.display = 'none';
        }
    });
}

// 点击背景关闭模态框
function closeModalOnBackgroundClick(event, modalId) {
    if (event.target.id === modalId) {
        closeAllModals();
    }
}

// ==================== 日志配置相关函数 ====================

// 显示日志配置对话框
function showLoggingConfigDialog() {
    console.log('显示日志配置对话框');
    addLog('info', '打开日志配置对话框');
    
    const modal = document.getElementById('logging-config-modal');
    if (modal) {
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
        loadCurrentLoggingConfig();
    } else {
        addLog('error', '日志配置对话框元素未找到');
    }
}

// 关闭日志配置对话框
function closeLoggingConfigDialog() {
    console.log('关闭日志配置对话框');
    const modal = document.getElementById('logging-config-modal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
}

// 加载当前日志配置
function loadCurrentLoggingConfig() {
    console.log('加载当前日志配置');
    addLog('info', '加载当前日志配置');
    
    fetch(`${API_BASE}/api/config/logging`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const config = data.data;
                console.log('当前日志配置:', config);
                
                // 设置日志级别
                const logModeSelect = document.getElementById('log-mode');
                if (logModeSelect) {
                    logModeSelect.value = config.log_mode || 'info';
                }
                
                // 设置日志格式
                const logFormatSelect = document.getElementById('log-format');
                if (logFormatSelect) {
                    logFormatSelect.value = config.log_format || '%(asctime)s - %(name)s - %(levelname)s - %(message)s';
                }
                
                // 设置输出方式
                const logToConsole = document.getElementById('log-to-console');
                const logToFile = document.getElementById('log-to-file');
                if (logToConsole) {
                    logToConsole.checked = config.log_to_console !== false;
                }
                if (logToFile) {
                    logToFile.checked = config.log_to_file !== false;
                }
                
                // 设置文件设置
                const maxFileSize = document.getElementById('max-file-size');
                const backupCount = document.getElementById('backup-count');
                if (maxFileSize) {
                    maxFileSize.value = Math.round((config.max_file_size || 10485760) / 1024 / 1024);
                }
                if (backupCount) {
                    backupCount.value = config.backup_count || 5;
                }
                
                addLog('success', '日志配置加载成功');
            } else {
                addLog('error', `加载日志配置失败: ${data.error}`);
            }
        })
        .catch(error => {
            console.error('加载日志配置异常:', error);
            addLog('error', `加载日志配置异常: ${error.message}`);
        });
}

// 应用日志配置
function applyLoggingConfig() {
    console.log('应用日志配置');
    addLog('info', '应用日志配置');
    
    // 收集配置数据
    const config = {
        log_mode: document.getElementById('log-mode').value,
        log_format: document.getElementById('log-format').value,
        log_to_console: document.getElementById('log-to-console').checked,
        log_to_file: document.getElementById('log-to-file').checked,
        max_file_size: parseInt(document.getElementById('max-file-size').value) * 1024 * 1024,
        backup_count: parseInt(document.getElementById('backup-count').value)
    };
    
    console.log('要应用的日志配置:', config);
    
    // 发送配置到API
    fetch(`${API_BASE}/api/config/logging`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(config)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            addLog('success', '日志配置应用成功');
            closeLoggingConfigDialog();
        } else {
            addLog('error', `应用日志配置失败: ${data.error}`);
        }
    })
    .catch(error => {
        console.error('应用日志配置异常:', error);
        addLog('error', `应用日志配置异常: ${error.message}`);
    });
}

// 测试日志配置
function testLoggingConfig() {
    console.log('测试日志配置');
    addLog('info', '测试日志配置');
    
    const testMessage = '这是一条测试日志消息 - ' + new Date().toLocaleString();
    const logLevel = document.getElementById('log-mode').value;
    
    fetch(`${API_BASE}/api/log/test`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            message: testMessage,
            level: logLevel
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            addLog('success', `测试日志发送成功: ${testMessage}`);
        } else {
            addLog('error', `测试日志发送失败: ${data.error}`);
        }
    })
    .catch(error => {
        console.error('测试日志异常:', error);
        addLog('error', `测试日志异常: ${error.message}`);
    });
}

// ==================== UART串口配置相关函数 ====================

// 显示UART配置对话框
function showUartConfigDialog() {
    const modal = document.getElementById('uart-config-modal');
    if (modal) {
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
        loadUartConfig();
    }
}

// 关闭UART配置对话框
function closeUartConfigDialog() {
    const modal = document.getElementById('uart-config-modal');
    if (modal) {
        modal.classList.add('hidden');
        modal.style.display = 'none';
    }
}

// 加载UART配置
async function loadUartConfig() {
    try {
        const response = await fetch(`${API_BASE}/api/uart/config`);
        const data = await response.json();
        
        if (data.success && data.config) {
            const config = data.config;
            document.getElementById('uart-port').value = config.port || '';
            document.getElementById('uart-baudrate').value = config.baudrate || 115200;
            document.getElementById('uart-timeout').value = config.timeout || 1.0;
            document.getElementById('uart-bytesize').value = config.bytesize || 8;
            document.getElementById('uart-parity').value = config.parity || 'N';
            document.getElementById('uart-stopbits').value = config.stopbits || 1;
        }
    } catch (error) {
        addLog('error', `加载UART配置失败: ${error.message}`);
    }
}

// 应用UART配置
async function applyUartConfig() {
    const config = {
        port: document.getElementById('uart-port').value,
        baudrate: parseInt(document.getElementById('uart-baudrate').value),
        timeout: parseFloat(document.getElementById('uart-timeout').value),
        bytesize: parseInt(document.getElementById('uart-bytesize').value),
        parity: document.getElementById('uart-parity').value,
        stopbits: parseInt(document.getElementById('uart-stopbits').value)
    };
    
    try {
        addLog('info', '正在设置UART配置...');
        const response = await fetch(`${API_BASE}/api/uart/config`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(config)
        });
        const data = await response.json();
        
        if (data.success) {
            addLog('success', 'UART配置设置成功');
            
            // 保存配置
            addLog('info', '正在保存UART配置...');
            const saveResponse = await fetch(`${API_BASE}/api/config/save`, {
                method: 'POST'
            });
            if (saveResponse.ok) {
                addLog('success', 'UART配置保存成功');
                addLog('info', '提示：请先点击"测试连接"按钮测试UART连接，然后可以开始监控日志');
                
                // 立即刷新状态，提供即时反馈
                await refreshStatus();
            } else {
                addLog('error', 'UART配置保存失败');
            }
            
            closeUartConfigDialog();
        } else {
            addLog('error', `UART配置设置失败: ${data.message}`);
        }
    } catch (error) {
        addLog('error', `设置UART配置异常: ${error.message}`);
    }
}

// 测试UART连接
async function testUartConnection() {
    try {
        addLog('info', '正在测试UART连接...');
        const response = await fetch(`${API_BASE}/api/uart/test`, {
            method: 'POST'
        });
        const data = await response.json();
        
        if (data.success) {
            addLog('success', `UART连接测试成功: ${data.message}`);
            showConnectionStatus('success', `UART串口 ${data.port} 连接测试成功！`);
        } else {
            addLog('error', `UART连接测试失败: ${data.message}`);
            showConnectionStatus('error', `UART串口连接测试失败: ${data.message}`);
        }
    } catch (error) {
        addLog('error', `测试UART连接异常: ${error.message}`);
        showConnectionStatus('error', `UART连接测试异常: ${error.message}`);
    }
}

// 连接UART串口
async function connectUart() {
    try {
        addLog('info', '正在连接UART串口...');
        const response = await fetch(`${API_BASE}/api/uart/connect`, {
            method: 'POST'
        });
        const data = await response.json();
        
        if (data.success) {
            addLog('success', `UART串口连接成功: ${data.message}`);
            showConnectionStatus('success', `UART串口连接成功！`);
            
            // 立即更新UART连接状态
            isUartConnected = true;
            
            // 立即刷新状态，显示连接状态
            await refreshStatus();
            
            // 关闭配置对话框
            closeUartConfigDialog();
        } else {
            addLog('error', `UART串口连接失败: ${data.message}`);
            showConnectionStatus('error', `UART串口连接失败: ${data.message}`);
        }
    } catch (error) {
        addLog('error', `连接UART串口异常: ${error.message}`);
        showConnectionStatus('error', `UART串口连接异常: ${error.message}`);
    }
}

// 断开UART串口
async function disconnectUart() {
    try {
        addLog('info', '正在断开UART串口...');
        const response = await fetch(`${API_BASE}/api/uart/disconnect`, {
            method: 'POST'
        });
        const data = await response.json();
        
        if (data.success) {
            addLog('success', `UART串口断开成功: ${data.message}`);
            showConnectionStatus('info', `UART串口已断开`);
            
            // 立即更新UART连接状态
            isUartConnected = false;
            
            // 立即刷新状态，显示连接状态
            await refreshStatus();
        } else {
            addLog('error', `UART串口断开失败: ${data.message}`);
            showConnectionStatus('error', `UART串口断开失败: ${data.message}`);
        }
    } catch (error) {
        addLog('error', `断开UART串口异常: ${error.message}`);
        showConnectionStatus('error', `UART串口断开异常: ${error.message}`);
    }
}

// 扫描UART端口
async function scanUartPorts() {
    try {
        addLog('info', '正在扫描UART端口...');
        const response = await fetch(`${API_BASE}/api/ports`);
        const data = await response.json();
        
        if (data.success && data.ports) {
            const portSelect = document.getElementById('uart-port');
            const detectedDiv = document.getElementById('detected-uart-ports');
            
            // 清空现有选项
            portSelect.innerHTML = '<option value="">请选择端口</option>';
            
            // 添加检测到的端口
            data.ports.forEach(port => {
                const option = document.createElement('option');
                option.value = port;
                option.textContent = port;
                portSelect.appendChild(option);
            });
            
            // 显示检测结果
            if (data.ports.length > 0) {
                detectedDiv.innerHTML = `检测到 ${data.ports.length} 个端口: ${data.ports.join(', ')}`;
                detectedDiv.style.color = '#00ff00';
            } else {
                detectedDiv.innerHTML = '未检测到可用端口';
                detectedDiv.style.color = '#ff4444';
            }
            
            addLog('success', `UART端口扫描完成，检测到 ${data.ports.length} 个端口`);
        } else {
            addLog('error', `UART端口扫描失败: ${data.message || '未知错误'}`);
        }
    } catch (error) {
        addLog('error', `扫描UART端口异常: ${error.message}`);
    }
}
